package com.muqi.app.network.http;

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import com.muqi.app.project.application.ActivitiesStack;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.LogUtil;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.login.LoginActivity;
import com.muqi.app.qlearn.student.R;

public class SyncHttpUtils {
	
	public enum RESULTCODE{
		FAILURE,
		ERROR ,
		LOCAL ,
		SUCCESS ,
		NONET ,
		PARSEERROR
		}
	
	private static SyncHttpClient client = new SyncHttpClient();// 实例对象
	
	static { 
        client.setTimeout(20000); // 设置链接超时，如果不设置，默认为10s
        client.setMaxRetriesAndTimeout(3, 60000);//重连次数和超时
    }
	
	public interface SyncCallBackListener {
		void onSyncCallBack(RESULTCODE resuleCode, String request, String result);
	}
	
	private static String getAbsoluteUrl(String relativeUrl) {
		String RequestUrl = NetWorkApi.SERVER_IP + relativeUrl;
		LogUtil.e("发送的请求"+RequestUrl);
		return RequestUrl;
	}
	
	/**
	 * 
	 * @param context 请求传入context，在destroy时取消未完成请求，避免僵尸请求
	 * @param urlString 
	 * @param listener 回调
	 */
	public static void get(final Context context, final String urlString, final SyncCallBackListener listener){
		if(NetWorkUtils.isNetworkAvailable(context)){
			client.get(context, getAbsoluteUrl(urlString), new TextHttpResponseHandler() {
				
				@Override
				public void onStart() {
					super.onStart();
				}
				
				@Override
				public void onProgress(int bytesWritten, int totalSize) {
					super.onProgress(bytesWritten, totalSize);
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					listener.onSyncCallBack(RESULTCODE.FAILURE, urlString, NetWorkApi.REQUEST_FAILED);
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, String arg2) {
					try {
						JSONObject resultAllata = new JSONObject(arg2.toString());
						int errcode = resultAllata.getInt("errcode");
						String errdesc = resultAllata.getString("errdesc");
						if (errcode == 0) {
							listener.onSyncCallBack(RESULTCODE.SUCCESS,urlString, arg2.toString());
						} else if(errcode == 90000){
							ShowToast.showShort(context, errdesc);
							Intent intent = new Intent();
							intent.setClass(context, LoginActivity.class);
							context.startActivity(intent);
							ActivitiesStack.getInstance().popAll(true);
						} else {
							ShowToast.showShort(context, errdesc);
							listener.onSyncCallBack(RESULTCODE.ERROR, urlString, "");
						}
					} catch (Exception e) {
						listener.onSyncCallBack(RESULTCODE.PARSEERROR,urlString, NetWorkApi.REQUEST_JSON_FAILED);
					}
				}
				
				@Override
				public void onFinish() {
					super.onFinish();
				}
				
				@Override
				public void onRetry(int retryNo) {
					LogUtil.e("请求"+getAbsoluteUrl(urlString)+"重连次数——"+retryNo);
					super.onRetry(retryNo);
				}
				
				@Override
				public void onCancel() {
					LogUtil.e("请求"+getAbsoluteUrl(urlString)+"取消");
					super.onCancel();
				}
			});
		}else{
			ShowToast.showShort(context, R.string.net_break);
			listener.onSyncCallBack(RESULTCODE.NONET,urlString, NetWorkApi.REQUEST_NETWORK_BREAKED);
		}
	}
	
	
/*********************************Post方法*************************************************/
	
	public static void post(final Context context, RequestParams params, final String urlString, final SyncCallBackListener listener){
		if(NetWorkUtils.isNetworkAvailable(context)){
			client.post(context, getAbsoluteUrl(urlString), params, new TextHttpResponseHandler() {
				
				@Override
				public void onStart() {
					super.onStart();
				}
				
				@Override
				public void onProgress(int bytesWritten, int totalSize) {
					super.onProgress(bytesWritten, totalSize);
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					listener.onSyncCallBack(RESULTCODE.FAILURE,urlString, NetWorkApi.REQUEST_FAILED);
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, String arg2) {
					try {
						JSONObject resultAllata = new JSONObject(arg2.toString());
						int errcode = resultAllata.getInt("errcode");
						String errdesc = resultAllata.getString("errdesc");
						if (errcode == 0) {
							listener.onSyncCallBack(RESULTCODE.SUCCESS,urlString, arg2.toString());
						} else {
							ShowToast.showShort(context, errdesc);
							listener.onSyncCallBack(RESULTCODE.ERROR,urlString,arg2.toString());
						}
					} catch (Exception e) {
						listener.onSyncCallBack(RESULTCODE.PARSEERROR,urlString, NetWorkApi.REQUEST_JSON_FAILED);
					}
				}
				
				@Override
				public void onFinish() {
					super.onFinish();
				}
				
				@Override
				public void onRetry(int retryNo) {
					LogUtil.e("请求"+getAbsoluteUrl(urlString)+"重连次数——"+retryNo);
					super.onRetry(retryNo);
				}
				
				@Override
				public void onCancel() {
					LogUtil.e("请求"+getAbsoluteUrl(urlString)+"取消");
					super.onCancel();
				}
			});
		}else{
			ShowToast.showShort(context, R.string.net_break);
			listener.onSyncCallBack(RESULTCODE.NONET, urlString, NetWorkApi.REQUEST_NETWORK_BREAKED);
		}
	}
}
